<template>
  <div>
    <BasicModal
      @register="registerModal"
      v-bind="$attrs"
      title="添加通知收件人组"
      :helpMessage="['查看帮助']"
      @ok="okClick"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form';
  import { ref } from 'vue';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';

  import { notificationsParams } from '/@/api/thingsborad/notification/model/notificationsModel';
  import {
    getTenantsList,
    gettenantProfiles,
    createTenant,
  } from '/@/api/thingsborad/notification/notification';
  let emits = defineEmits(['sysCloseFlag']);
  //租户下拉列表
  let usersListOptions = ref<any>([]);
  // 租户配置下拉列表
  let tanentListOptions = ref<any>([]);

  //请求参数
  let params = ref<notificationsParams>({
    pageSize: 50,
    page: 0,
    sortProperty: 'email',
    sortOrder: 'ASC',
  });
  const schemas: FormSchema[] = [
    {
      field: 'ReceivingName',
      required: true,
      component: 'Input',
      label: '收件人名称',
      componentProps: {
        placeholder: '请输入收件人名称',
      },
    },
    {
      field: 'switchType',
      component: 'RadioGroup',
      label: '类型',

      defaultValue: 'PLATFORM_USERS',
      componentProps: {
        options: [
          {
            label: '平台用户',
            value: 'PLATFORM_USERS',
          },
          {
            label: 'Slack',
            value: 'SLACK',
          },
          {
            label: 'Microsoft Teams',
            value: 'MICROSOFT_TEAMS',
          },
        ],
      },
    },
    {
      ifShow: (value) => {
        return value.model.switchType === 'SLACK';
      },
      field: 'channelType',
      component: 'RadioGroup',
      label: 'Slack 频道类型',

      defaultValue: 'publicChannel',
      componentProps: {
        options: [
          {
            label: '公开频道',
            value: 'publicChannel',
          },
          {
            label: '私有频道',
            value: 'privateChannel',
          },
          {
            label: '直接消息',
            value: 'directMessage',
          },
        ],
      },
    },
    {
      ifShow: (value) => {
        return value.model.switchType === 'SLACK';
      },
      field: 'dialogue',
      component: 'Input',
      required: true,
      label: '对话',

      componentProps: {
        placeholder: '请输入对话内容',
      },
    },
    {
      ifShow: (value) => {
        return value.model.switchType === 'MICROSOFT_TEAMS';
      },
      field: 'webhookURL',
      component: 'Input',
      required: true,
      label: 'WebhookURL',

      componentProps: {
        placeholder: '请输入Webhook URL',
      },
    },
    {
      ifShow: (value) => {
        return value.model.switchType === 'MICROSOFT_TEAMS';
      },
      field: 'channelName',
      component: 'Input',
      required: true,
      label: 'ChannelName',

      componentProps: {
        placeholder: '请输入Channel Name',
      },
    },
    {
      ifShow: (value) => {
        return value.model.switchType === 'PLATFORM_USERS';
      },
      field: 'userFilter',
      component: 'Select',
      label: '用户筛选器',
      defaultValue: 'ALL_USERS',
      required: true,
      componentProps: {
        options: [
          {
            label: '所有用户',
            value: 'ALL_USERS',
          },
          {
            label: '租户管理员',
            value: 'TENANT_ADMINISTRATORS',
          },
          {
            label: '受影响的租户管理员',
            value: 'AFFECTED_TENANT_ADMINISTRATORS',
          },
          {
            label: '系统管理员',
            value: 'SYSTEM_ADMINISTRATORS',
          },
        ],
      },
    },
    {
      ifShow: (value) => {
        return (
          value.model.switchType === 'PLATFORM_USERS' &&
          value.model.userFilter === 'TENANT_ADMINISTRATORS'
        );
      },
      field: 'isUseModal',
      component: 'RadioButtonGroup',
      label: '',
      colProps: {
        span: 24,
      },
      defaultValue: 'tenant',
      componentProps: {
        style: {
          width: '100%',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          marginBottom: '-200px',
          marginTop: '-20px',
        },
        options: [
          {
            label: '租   户',
            value: 'tenant',
          },
          {
            label: '租户配置',
            value: 'tenantConfig',
          },
        ],
      },
    },
    {
      ifShow: (value) => {
        return (
          value.model.switchType === 'PLATFORM_USERS' &&
          value.model.userFilter === 'TENANT_ADMINISTRATORS' &&
          value.model.isUseModal === 'tenant'
        );
      },
      field: 'tanentList',
      component: 'Select',
      label: '租户列表  ( 如果字段为空，触发器将应用于所有租户)',
    },
    {
      ifShow: (value) => {
        return (
          value.model.switchType === 'PLATFORM_USERS' &&
          value.model.userFilter === 'TENANT_ADMINISTRATORS' &&
          value.model.isUseModal === 'tenantConfig'
        );
      },
      field: 'tenantConfigList',
      component: 'Select',
      label: '租户配置  (  如果字段为空，触发器将应用于所有租户配置文件)',
    },
    {
      field: 'describe',
      component: 'Input',
      label: '描述',
      colProps: {
        span: 24,
      },
      componentProps: {
        placeholder: '请输入描述信息',
        style: {
          height: '55px',
        },
      },
    },
  ];
  // 表格初始化
  const [registerForm, { updateSchema, validate, resetFields, setFieldsValue }] = useForm({
    layout: 'vertical',
    schemas,
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });
  // 获取租户下拉列表数据
  async function getUsersListSelect(params: notificationsParams) {
    usersListOptions.value = [];
    try {
      const userData = await getTenantsList(params);
      userData.data.forEach((item) => {
        usersListOptions.value.push({
          value: item.id.id,
          label: item.name,
        });
      });
    } catch (error) {
      console.error('获取数据时出错：', error);
      // 处理错误情况
    }
  }
  // 获取租户配置下拉列表数据
  async function getTaneanListSelect(params: notificationsParams) {
    tanentListOptions.value = [];
    try {
      const userData = await gettenantProfiles(params);
      userData.data.forEach((item) => {
        tanentListOptions.value.push({
          value: item.id.id,
          label: item.name,
        });
      });
    } catch (error) {
      console.error('获取数据时出错：', error);
      // 处理错误情况
    }
  }

  //用户客户下拉表单数据填充更新
  const [registerModal, { closeModal, setModalProps }] = useModalInner(async (data) => {
    resetFields();

    setModalProps({
      showCancelBtn: false,
      showOkBtn: false,
      width: 800,
      loading: false,
      confirmLoading: false,
      ...modalStyleSetting,
    });
    if (data !== true) {
      //Microsoft Teams
      if (data.type === 'Microsoft Teams') {
        setFieldsValue({
          ReceivingName: data.name,
          switchType: 'MICROSOFT_TEAMS',
          webhookURL: data.info.configuration.webhookUrl,
          channelName: data.info.configuration.channelName,
          describe: data.description,
        });
      } //平台用户
      else if (data.type === '平台用户') {
        setFieldsValue({
          ReceivingName: data.name,
          switchType: 'PLATFORM_USERS',
          userFilter: data.info.configuration.usersFilter.type,
          describe: data.description,
        });
        //租户赋值
        if (data.info.configuration.usersFilter.tenantsIds !== null) {
          setFieldsValue({
            tanentList: data.info.configuration.usersFilter.tenantsIds,
          });
        } //租户配置赋值
        else if (data.info.configuration.usersFilter.tenantProfilesIds !== null) {
          setFieldsValue({
            tenantConfigList: data.info.configuration.usersFilter.tenantProfilesIds,
          });
        }
      } //SLACK
      else {
        setFieldsValue({
          ReceivingName: data.name,
          switchType: 'SLACK',
          describe: data.description,
        });
      }
    }

    //租户下拉数据赋值
    params.value.sortProperty = 'email';
    await getUsersListSelect(params.value);
    await updateSchema({
      field: 'tanentList',
      componentProps: {
        listHeight: 160,
        mode: 'multiple',
        options: usersListOptions.value,
      },
    });

    //租户配置下拉数据赋值
    params.value.sortProperty = 'name';
    await getTaneanListSelect(params.value);
    await updateSchema({
      field: 'tenantConfigList',
      componentProps: {
        listHeight: 160,
        mode: 'multiple',
        options: tanentListOptions.value,
      },
    });
  });
  //创建收件人确实点击事件
  async function okClick() {
    const formData = await validate();
    
    let createTargetsParams: any = {
      name: formData.ReceivingName,
      configuration: {
        type: formData.switchType,
        description: formData.describe,
      },
    };
    //平台用户
    if (formData.switchType === 'PLATFORM_USERS') {
      createTargetsParams.configuration['usersFilter'] = { type: formData.userFilter };
      if (formData.userFilter === 'TENANT_ADMINISTRATORS') {
        if (formData.isUseModal === 'tenant') {
          createTargetsParams.configuration.usersFilter['tenantsIds'] = formData.tanentList;
        } else {
          createTargetsParams.configuration.usersFilter['tenantProfilesIds'] =
            formData.tenantConfigList;
        }
      }
    }
    //Microsoft Teams
    if (formData.switchType === 'MICROSOFT_TEAMS') {
      createTargetsParams.configuration['webhookUrl'] = formData.webhookURL;
      createTargetsParams.configuration['channelName'] = formData.channelName;
    }

    let tanentData = await createTenant(createTargetsParams);
    await resetFields();
    emits('sysCloseFlag', tanentData);
    closeModal();
  }
</script>
